package Class014;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

//用栈实现队列
//用队列实现栈
public class StackAndQueue {
    public static void main(String[] args) {
//        StackQueue stackQueue = new StackQueue();
//        stackQueue.offer(1);
//        stackQueue.offer(2);
//        stackQueue.offer(3);
//        System.out.println(stackQueue.poll());
//        stackQueue.offer(4);
//        System.out.println(stackQueue.peek());
//        System.out.println(stackQueue.poll());
//        System.out.println(stackQueue.poll());
//        System.out.println(stackQueue.poll());
//        System.out.println(stackQueue.poll());

        QueueStack queueStack = new QueueStack();
        queueStack.push(1);
        queueStack.push(2);
        queueStack.push(3);
        System.out.println(queueStack.pop());
        queueStack.push(4);
        System.out.println(queueStack.peek());
        System.out.println(queueStack.pop());
        System.out.println(queueStack.pop());
        System.out.println(queueStack.pop());
    }

    public static class StackQueue {
        public Stack<Integer> store;
        public Stack<Integer> out;

        public StackQueue(){
            store = new Stack<>();
            out = new Stack<>();
        }

        public void offer(int val) {
            store.push(val);
        }

        public int peek() {
            if(isEmpty()) {
                System.out.println("Already Full!");
                return -114514;
            }
            if(out.isEmpty()) {
                while(!store.isEmpty()) {
                    out.push(store.pop());
                }
            }
            return out.peek();
        }

        public int poll() {
            if(isEmpty()) {
                System.out.println("Already Full!");
                return -114514;
            }
            if(out.isEmpty()) {
                while(!store.isEmpty()) {
                    out.push(store.pop());
                }
            }
            return out.pop();
        }

        public boolean isEmpty() {
            return out.isEmpty() && store.isEmpty();
        }

    }

    public static class QueueStack {
        public Queue<Integer> queue;

        public QueueStack() {
            queue = new LinkedList<>();
        }

        public void push(int val) {
            queue.offer(val);
            int size = queue.size();
            while(size > 1) {
                queue.offer(queue.poll());
                size--;
            }
        }

        public int pop() {
            return queue.isEmpty() ? -114514 : queue.poll();
        }

        public int peek() {
            return queue.isEmpty() ? -114514 : queue.peek();
        }
    }
}
